package pdmlconverter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class PdmlConverter {

	// public final static String FROM_LOG_FOLDER = "E:/WireSharkLog/19052010/";

	public static String FROM_LOG_FOLDER = "/C:/eclipseProjects/securityProject/files/from/";
	public static String TO_LOG_FOLDER = "C:/eclipseProjects/securityProject/files/to/";
	public static String TSHARK_FOLDER = "/C:/eclipseProjects/securityProject/files/from/";

	private static long lastModifiedFileTime = 0;

	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub

		boolean shouldDelete = false;

		if ((args.length != 3) || (null == args[0]) || (null == args[1])
				|| (null == args[2]))
			errorInArguments();
		FROM_LOG_FOLDER = args[0];
		TO_LOG_FOLDER = args[1];
		if (args[2].equals("1"))
			shouldDelete = true;

		long curFolderLastModifiedTime = 0;
		long curFileLastModifiedTime;

		File logFolder = new File(FROM_LOG_FOLDER);

		while (true) {

			if (!shouldDelete) {
				curFolderLastModifiedTime = lastModifiedFileTime;
			}
			for (File logfile : logFolder.listFiles()) {

				if (!shouldDelete) {
					curFileLastModifiedTime = logfile.lastModified();
					if (curFileLastModifiedTime > curFolderLastModifiedTime) {
						if (curFileLastModifiedTime > lastModifiedFileTime) {
							lastModifiedFileTime = curFileLastModifiedTime;
						}

					} else {
						continue;
					}
				}

				Process process;
				try {

					// System.out.println(logfile.getPath());
					int pos1 = logfile.getPath().lastIndexOf('\\');
					int pos2 = logfile.getPath().lastIndexOf('.');
					String newstring = logfile.getPath().substring(pos1 + 1,
							pos2 + 1);
					newstring += "pdml";

					// System.out.println(newstring);
					// System.out.println(logfile.getAbsolutePath());

					System.out.println("Starting converting....");

					process = Runtime.getRuntime().exec(
							"cmd /c tshark -r " + logfile
									+ " -R http.request -T pdml > " + TO_LOG_FOLDER
									+ "tmp_" + newstring);

					process.waitFor();

					File tmpFile = new File(TO_LOG_FOLDER + "tmp_" + newstring);

					if (tmpFile.exists()) {

						System.out.println("Finished converting.");
						System.out.println("Starting prefix rule....");
						
						File finalFile = new File(TO_LOG_FOLDER + newstring);
						finalFile.createNewFile();
						
						process = Runtime.getRuntime().exec(
								"cmd /c E:/PdmlConverter/procTORfile-v3.bat " + TO_LOG_FOLDER
										+ "tmp_" + newstring + " " + TO_LOG_FOLDER + newstring);

						process.waitFor();
						
//						// Run prefix rule (it removes not important data of the
//						// file)
//						File finalFile = new File(TO_LOG_FOLDER + newstring);
//						finalFile.createNewFile();
//						try {
//							ruleFilter(TO_LOG_FOLDER + "tmp_" + newstring,
//									TO_LOG_FOLDER + newstring,
//									"wireshark-basic-v3.xslt");
//						} catch (TransformerConfigurationException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						} catch (ParserConfigurationException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						} catch (TransformerFactoryConfigurationError e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						} catch (SAXException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						} catch (TransformerException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}

						System.out.println("Finished prefix rule.");

						if (finalFile.length() != 0) {
							// causes problem, when file not finished
							System.out
									.println("Starting deletion of tmp files....");
							
							int i = 0;
							while ((!(tmpFile.delete())) && (i < 10)) {
								System.out.println("Deleting file "
										+ TO_LOG_FOLDER + "tmp_" + newstring
										+ " Failed, trying again...");
								Thread.sleep(10000);
								i++;
							}
							System.out
									.println("Finished deletion of tmp files.");

							if ((shouldDelete) && (i < 10)) {
								if (!logfile.canWrite())
									throw new IllegalArgumentException(
											"Delete: write protected: ");

								// while (!logfile.delete()){
								// System.out.println("Deleting file " +
								// logfile.getName() +
								// " Failed, trying again...");
								// Thread.sleep(1000);
								// }

								System.out
										.println("Starting deletion of pcap file");
								// Attempt to delete it
								boolean success = logfile.delete();

								if (!success)
									System.out.println("Deleting file "
											+ logfile.getName()
											+ " Failed, trying again...");
								// throw new IllegalArgumentException(
								// "Delete: deletion failed");
								else
									System.out
											.println("Finished deletion of pcap file");
							}
						}
						
					} else {
						System.out.println("Converting Faild, Trying again");
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		// System.out.println("yoyo");

	}

	static void errorInArguments() {
		System.out
				.println("Arguments are: (1)From folder, (2)To folder, (3) 0/1 - 1 for deleting files after converting.\n"
						+ "Example: C:\\from\\ C:\\to\\ 1");
		System.exit(0);

	}

	static void ruleFilter(String fromFilename, String toFilename,
			String ruleFileName) throws ParserConfigurationException,
			TransformerFactoryConfigurationError, SAXException, IOException,
			TransformerConfigurationException, TransformerException,
			FileNotFoundException {
		DocumentBuilder dBuilder;
		// Instantiate a DocumentBuilderFactory.
		javax.xml.parsers.DocumentBuilderFactory dfactory = javax.xml.parsers.DocumentBuilderFactory
				.newInstance();
		dBuilder = dfactory.newDocumentBuilder();

		TransformerFactory tFactory = TransformerFactory.newInstance();
		// Use the DocumentBuilder to parse the XML input.
		Document inDoc = dBuilder.parse(fromFilename);

		// Generate a Transformer.
		Transformer transformer = tFactory.newTransformer(new StreamSource(
				ruleFileName));

		FileOutputStream fileOut = new FileOutputStream(toFilename);
		transformer.transform(new DOMSource(inDoc), new StreamResult(fileOut));

		fileOut.flush();
		fileOut.close();
	}

}
